package com.link.play.fit.ai.ui.view

import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import android.view.ViewConfiguration
import android.widget.FrameLayout
import androidx.core.view.marginBottom
import androidx.core.view.marginEnd
import androidx.core.view.marginLeft
import androidx.core.view.marginRight
import androidx.core.view.marginStart
import androidx.core.view.marginTop
import androidx.customview.widget.ViewDragHelper
import com.link.play.fit.ai.R

/**
 *Create by SleepDog on 2025-04-10
 */
class DraggableContainer @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr) {

    private lateinit var viewDragHelper: ViewDragHelper
    private var draggedView: View? = null

    // 系统认为的最小滑动距离
    private val touchSlop = ViewConfiguration.get(context).scaledTouchSlop

    // 记录初始位置
    private var downX = 0f
    private var downY = 0f
    private var isDragging = false

    init {
        // 初始化 ViewDragHelper
        viewDragHelper = ViewDragHelper.create(this, 1.0f, object : ViewDragHelper.Callback() {

            // 判断是否可以捕获子视图
            override fun tryCaptureView(child: View, pointerId: Int): Boolean {
                // 只允许拖动特定的视图（比如 ImageView）
                return child.id == R.id.draggableImage
            }

            // 限制拖动的范围（水平方向）
            override fun clampViewPositionHorizontal(child: View, left: Int, dx: Int): Int {
                // 限制水平拖动范围
                val containerWidth = width - child.width - child.marginRight
                return child.marginLeft.coerceAtLeast(left.coerceAtMost(containerWidth))
            }

            // 限制拖动的范围（垂直方向）
            override fun clampViewPositionVertical(child: View, top: Int, dy: Int): Int {
                // 限制垂直拖动范围
                val containerHeight = height - child.height - child.marginBottom
                return 0.coerceAtLeast(top.coerceAtMost(containerHeight))
            }

            // 当视图被释放时的回调
            override fun onViewReleased(releasedChild: View, xvel: Float, yvel: Float) {
                super.onViewReleased(releasedChild, xvel, yvel)
                if (!isDragging) return
                // 吸附到最近边缘的逻辑
                val containerWidth = width - releasedChild.width
                val containerHeight = height - releasedChild.height

                // 计算到四个边缘的距离
                val leftDistance = releasedChild.left.toFloat()
                val rightDistance = (containerWidth - releasedChild.left).toFloat()
                val topDistance = releasedChild.top.toFloat()
                val bottomDistance = (containerHeight - releasedChild.top).toFloat()

                // 找出最近的边缘
                val minDistance =
                    listOf(leftDistance, rightDistance, topDistance, bottomDistance).minOrNull()
                        ?: 0f

                val targetX: Int
                val targetY: Int

                if (minDistance == leftDistance) {
                    // 吸附到左边
                    targetX = releasedChild.marginStart
                    targetY = releasedChild.top
                } else if (minDistance == rightDistance) {
                    // 吸附到右边
                    targetX = containerWidth - releasedChild.marginEnd
                    targetY = releasedChild.top
                } else if (minDistance == topDistance) {
                    // 吸附到顶部
                    targetX = releasedChild.left
                    targetY = 0
                } else {
                    // 吸附到底部
                    targetX = releasedChild.left
                    targetY = containerHeight - releasedChild.marginBottom
                }

                // 平滑滑动到目标位置
                viewDragHelper.settleCapturedViewAt(targetX, targetY)
                invalidate()
            }
        })
    }

    override fun onInterceptTouchEvent(event: MotionEvent): Boolean {
        when (event.action) {
            MotionEvent.ACTION_DOWN -> {
                val x = event.x.toInt()
                val y = event.y.toInt()
                for (i in 0 until childCount) {
                    val child = getChildAt(i)
                    if (child.id == R.id.draggableImage) {
                        if (child.left <= x && x <= child.right && child.top <= y && y <= child.bottom) {
                            return true
                        }

                    }
                }
            }
        }
        return super.onInterceptTouchEvent(event)
    }

    // 处理触摸事件
    override fun onTouchEvent(event: MotionEvent): Boolean {
        viewDragHelper.processTouchEvent(event)
        when (event.action) {
            MotionEvent.ACTION_DOWN -> {
                val x = event.x.toInt()
                val y = event.y.toInt()
                isDragging = false
                for (i in 0 until childCount) {
                    val child = getChildAt(i)
                    if (child.id == R.id.draggableImage) {
                        if (child.left <= x && x <= child.right && child.top <= y && y <= child.bottom) {
                            // 记录按下位置
                            downX = event.rawX
                            downY = event.rawY
                            draggedView = child
                            return true
                        } else {
                            downX = 0f
                            downY = 0f
                            return false
                        }
                    }
                }
            }

            MotionEvent.ACTION_MOVE -> {
                if (downX != 0f || downY != 0f) {
                    // 判断是否达到拖动阈值
                    if (!isDragging) {
                        val dx = event.rawX - downX
                        val dy = event.rawY - downY
                        isDragging = dx * dx + dy * dy > touchSlop * touchSlop
                    }
                    return true
                }
                return false
            }

            MotionEvent.ACTION_UP -> {
                downX = 0f
                downY = 0f
                // 未达到拖动阈值时触发点击
                if (!isDragging) {
                    draggedView?.performClick()
                    return true
                } else return true
            }
        }
        return false
    }

    // 在每一帧中更新视图的位置
    override fun computeScroll() {
        if (viewDragHelper.continueSettling(true)) {
            invalidate()
        }
    }
}